<?php

namespace App\Http\Controllers\Admin;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Models\Product;
use App\Models\ProductSku;

class ProductsController extends Controller
{

    // 删除商品
    public function del(Request $request){
        $product = Product::find($request->id);
        $bool = $product->delete();
        if($bool){
            return response()->json(['status'=>200,'msg'=>'商品删除成功!','skus'=>$product]);
        }else{
            return response()->json(['status'=>3000,'msg'=>'商品删除失败!','skus'=>$product]);
        }
        
        
     }

    // 获取商品所属所有规格
    public function skus(Request $request){
       $product = Product::find($request->id);
       return response()->json(['status'=>200,'msg'=>'获取成功!','skus'=>$product->skus]);
    }

    // 添加sku商品;
    public function add_sku(Request $request){
        $sku = ProductSku::create($request->only(['title', 'description', 'price', 'stock','product_id']));
        return response()->json(['sku'=>$sku,'msg'=>"规格添加成功",'status'=>200]);
    }

    // 更新sku商品;
    public function update_sku(Request $request){

        $sku = ProductSku::find($request->id);
        $sku->title = $request->title;
        $sku->description = $request->description;
        $sku->price = $request->price;
        $sku->stock = $request->stock;
        $sku->product_id = $request->product_id;

        $bool = $sku->save();

        if($bool){
            return response()->json(['sku'=>$sku,'msg'=>"规格更新成功!",'status'=>200]);
        }else{
            return response()->json(['sku'=>$sku,'msg'=>"规格更新失败!",'status'=>3000]);
        }

    }

    // 删除商品规格
    public function del_sku(Request $request){

        $sku = ProductSku::find($request->id);
        $bool = $sku->delete();

        if($bool){
            return response()->json(['sku'=>$sku,'msg'=>"规格删除成功!",'status'=>200]);
        }else{
            return response()->json(['sku'=>$sku,'msg'=>"规格删除失败!",'status'=>3000]);
        }

    }



    // 获取商品列表;
    public function list(Request $request){

        $size = $request->size ? $request->size : 5;

        if($request->pid){
            return Product::where('pid',$request->pid)->orderBy('created_at','desc')->paginate($size);
        }else{
            return Product::orderBy('created_at','desc')->paginate($size);
        }

    }

    // 更新商品状态
    public function state(Request $request){

        $product = Product::find($request->id);
        $product->on_sale = $request->on_sale;
        $bool = $product->save();
        
        if($bool){
            return response()->json(['meta'=>['status'=>200,'msg'=>'状态更新成功!'],'data'=>$product]);
        }else{
            return response()->json(['meta'=>['status'=>200,'msg'=>'状态更新失败!'],'data'=>$product]);
        }
        
    }


    // 商品详情
    // 获取房屋详情
    public function detail(Request $request){


        $product = Product::find($request->id);

        if(strlen($product->image)>6){
            $product->image = $this->getImgArr($product->image);
        }else{
            $product->image = Array();
        }

        return $product;

    }


    // 获取商品所有图片
    private function getImgArr($str){

        $imgArr = explode("&", $str);

        foreach($imgArr as $k=>$imgName){
            $imgArr[$k] =  config('app.upload').$imgName;
        }
        return $imgArr;

    }


    //更新商品
    public function update(Request $request){

        // 1 先上传3张图片;
        $pics = $request->file("pic");
        $picStr = "";

        if($pics){

            $path = \base_path("/public/upload/");

            

            foreach($pics as $k=>$file){
                $ext = $file->getClientOriginalExtension();
                $picName = time().rand(0,999).".".$ext;
                $file->move($path,$picName);
                $picStr =  $picStr."&".$picName;
                if($k==0){
                    $this->imageResize($path,$picName,200,160);
                }
            }
            
        }
        
        // 2 将其他表单数据转为php数组;
        $arr = json_decode($request->form,true);
        $arr['price'] = 0.00;

        // 3 把图片字符串保存到数组中;
        $arr["image"] = trim($picStr,"&");

        $product = Product::find($arr['id']);
        $product->pid = $arr['pid'];
        $product->title = $arr['title'];
        $product->image = $product->image ? $product->image.'&'.$arr["image"]:$arr["image"];
        $product->image = trim($product->image,'&');
        $product->description = $arr['description'];
        $product->on_sale = $arr['on_sale'];

        $res = $product->save();

        if($res){
            return response()->json(['meta'=>['status'=>200,'msg'=>'商品更新成功!'],'data'=>$product]);
        }else{
            return response()->json(['meta'=>['status'=>200,'msg'=>'商品更新失败!'],'data'=>$product]);
        }
        
   }

    //创建商品
    public function store(Request $request){

         // 1 先上传3张图片;
         $pics = $request->file("pic");
         $path = \base_path("/public/upload/");
         $picStr = "";

         foreach($pics as $k=>$file){
              $ext = $file->getClientOriginalExtension();
              $picName = time().rand(0,999).".".$ext;
              $file->move($path,$picName);
              $picStr .= "&".$picName;
              if($k==0){
                  $this->imageResize($path,$picName,200,160);
              }
         }

         // 2 将其他表单数据转为php数组;
         $arr = json_decode($request->form,true);
         $arr['price'] = 0.00;

         // 3 把图片字符串保存到数组中;
         $arr["image"] = ltrim($picStr,"&");

         // 4 表单数据(保护图片信息)
          $product = Product::create($arr);

        return response()->json(['meta'=>['status'=>200,'msg'=>'商品发布成功!'],'data'=>$product]);

    }

    // 生成缩略图;
    private function imageResize($path, $picname, $maxW=100, $maxH=100, $pre='s_')

{

    //2.去除path路径右侧的 /，再加上
    $path = rtrim($path,'/').'/';

    //3.获取一张图片详细信息
    $info = getimagesize($path.$picname);

    //4.根据用户上传的图像的类型，来判断我们需要用哪一个函数生成画布(imagejpeg、imagepng、imagegif)
    switch($info[2]){
        case "1":   //gif
            $oldImg = imagecreatefromgif($path.$picname);
            break;

        case "2":   //jpg
            $oldImg = imagecreatefromjpeg($path.$picname);
            break;

        case "3":   //png
            $oldImg = imagecreatefrompng($path.$picname);
            break;
    }

    //5.获取原图的宽高
    $oldW = imagesx($oldImg);
    $oldH = imagesy($oldImg);

    //6.判断原图的宽高那个边比较长
    if($oldW > $oldH){

        //计算比例
        $b = $oldW / $maxW;

        //计算缩放后的新的宽度与高度
        $newW = $oldW / $b;
        $newH = $oldH / $b;
    }else{

        //计算比例
        $b = $oldH / $maxH;

        //计算缩放后的新的宽度与高度
        $newW = $oldW / $b;
        $newH = $oldH / $b;
    }

    //7.根据缩放后的宽度与高度，生成一个新的画布
    $newImg = imagecreatetruecolor($newW, $newH);

    //8.开始缩放
    imagecopyresampled($newImg, $oldImg, '0','0','0','0',$newW,$newH,$oldW,$oldH);

    //9.根据原图的类型，生成对应的图像
    switch($info[2]){
        case "1":
            imagegif($newImg, $path.$pre.$picname); //./Uplods/s_123.jpg
            break;

        case "2":
            imagejpeg($newImg, $path.$pre.$picname);
            break;

        case "3":
            imagepng($newImg, $path.$pre.$picname);
            break;
    }

    //10.释放资源
    imagedestroy($oldImg);
    imagedestroy($newImg);
   }


   // 删除图片
   public function del_img(Request $request){

    // 根据id查找房源
    $product = Product::find($request->id);

    $imgArr = explode("&",$product->image);


    // 上传图片路径
    $imgPath = base_path('public/upload/');

    $file = $imgPath.$request->img;
    $small_file = $imgPath.'s_'.$request->img;


    // 删除大图
    if(file_exists($file)){
        unlink($file);
    }

    // 删除小图
    if(file_exists($small_file)){
        unlink($small_file);
    }

    $index = $this->getImgIndex($request->img,$imgArr);


    // 数据库删除;
    array_splice($imgArr, $index, 1);
    $product->image = implode('&',$imgArr);
    $bool = $product->save();

    // 返回数据
    if($bool){
        return response()->json(['meta'=>['msg'=>'删除成功!','status'=>200,'file'=>$file]]);
    }else{
        return response()->json(['meta'=>['msg'=>'删除失败!','status'=>3000]]);
    }


  }

  // 获取当前图片索引值
  private function getImgIndex($img,$imgArr){
       foreach($imgArr as $index => $val){
           if($img == $val)
              return $index;
       }
  }

}
